//define the javascript constant variable at first.
//var _CONTEXT_PATH = "/book99/";

//define the datetime format
var _CONTEXT_PATH = "/project4u/";
var DATETIME_FORMAT = "%Y-%m-%d";

var ACTION_INSERT = "INSERT";
var ACTION_DELETE = "DELETE";
var ACTION_UPDATE = "UPDATE";
var ACTION_VIEW   = "VIEW";
var ACTION_SAVE   = "SAVE";

//var GRID_LINK_COL_BGCOLOR  ="#CCCCFF";
//var GRID_LINK_COL_TEXTCOLOR="BLUE";
var GRID_LINK_CSS = "cursor:hand;cursor:pointer;color:blue;";

/*var sDiv1 = String.fromCharCode(1);
var sDiv2 = String.fromCharCode(2);
var sDiv3 = String.fromCharCode(3);
var sDiv4 = String.fromCharCode(4);
*/
String.prototype.trim = function() {
    return this.replace(/(^[\s]*)|([\s]*$)/g, "");
}
String.prototype.lTrim = function() {
    return this.replace(/(^[\s]*)/g, "");
}
String.prototype.rTrim = function() {
    return this.replace(/([\s]*$)/g, "");
}
String.prototype.replaceAll = function(search, replace){
	var regex = new RegExp(search, "g");
	return this.replace(regex, replace);
}
/*在字符串str的左边或右边添加指定的字符串到指定的长度
 *@param pstr 要附加的字符串
 *@param len  附加后字符串的长度
 *@param pointer 附加的方向，RIGHT OR LEFT
 */
String.prototype.strpad = function(pstr,len,pointer) {
    if (pstr==null || pstr=="") pstr = " ";
    var str = this;
    
    while (str.length < len) {
        if (pointer.toUpperCase() == "LEFT") {
            str = pstr + str;
        } else { //default is RIGHT
            str = str + pstr;
        }
    }
    return str;
}

Array.prototype.indexOf = function(sElement) {
	var iIndex=-1;
	for (var i=0; i<this.length; i++) {
		if (this[i] == sElement) {
			iIndex = i;
			break;
		}
	}
	return iIndex;
}

function msg(objInput,str,mode)
{
    str = html2str(str);
    str = str.replaceAll("<br/>" ,"\n");
    if (mode == 1)
    {
        alert(str);
        if (objInput!=null && !objInput.disabled) objInput.focus();
        return false;
    }
    else if (mode == 2)
    {
        return confirm(str);
    }
    else
    {
        return false;
    }
}

var http_request = false;
var http_return  = true;
function send_request(sUrl,argValue,func) {
	send_request1(sUrl,argValue,func,false);
}
//func -- 所对应的处理函数；isSync -- 是否不同步处理，true则不同步，false则同步
function send_request1(sUrl,argValue,func,isSync) {//初始化、指定处理函数、发送请求的函数
	http_request = false;
	sUrl = sUrl+"?"+encodeURI(argValue)+"&strNow="+getSysTime();

	if (window.XMLHttpRequest) { //Mozilla 浏览器
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) { //设置MiME类别
			http_request.overrideMimeType("text/xml");
		}
	}
	else if (window.ActiveXObject) { // IE浏览器
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) { // 异常，创建对象实例失败
		window.alert("Create XMLHttpRequest Object Failure!");
		return false;
	}
	http_request.onreadystatechange = func;
	// 确定发送请求的方式和URL以及是否同步执行下段代码
	http_request.open("GET", sUrl, isSync);
	//xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	//xmlhttp.setRequestHeader("Content-Type","text/xml");
	//xmlhttp.setRequestHeader("Content-Type","gb2312");

	http_request.send(null);
}

/**request function, with send_request1 function*/
function checkRequest() {
	if (http_request.readyState==4 && http_request.status==200) {
		http_return = http_request.responseText;
	}
}

function setTableRowColor(t) {
    for(var i = 0; i < t.rows.length; i++) {
        t.rows[i].style.height = "20px";
        if ( (i % 2) == 0) {
            t.rows[i].style.backgroundColor = "white";
        } else {
            t.rows[i].style.backgroundColor = "#EFEFEF";
        }
    }
}

function calcUTFByte(str)
{
	var len=0;

	for (var i=0;i<str.length;i++)
	{
		if (str.charCodeAt(i)>255) 
			len+=3; //unicode is 3 bytes, chinese and japanese are 2 bytes;
		else 
			len++;
	}
	return len;
}

function calcGBKByte(str)
{
	var len=0;

	for (var i=0;i<str.length;i++)
	{
		if (str.charCodeAt(i)>255) 
			len+=2; //unicode is 3 bytes, chinese and japanese are 2 bytes;
		else 
			len++;
	}
	return len;
}

function checkIsInteger(str)
{
    //如果为空，则通过校验
    if(str == "")
        return true;
    if(/^(\-?)(\d+)$/.test(str))
        return true;
    else
        return false;
}

function checkIsDouble(str)
{
    //如果为空，则通过校验
    if(str == "")
        return true;
    //如果是整数，则校验整数的有效性
    if(str.indexOf(".") == -1)
    {
        if(checkIsInteger(str) == true)
            return true;
        else
            return false;
    }
    else
    {
        if(/^(\-?)(\d+)(.{1})(\d+)$/g.test(str))
            return true;
        else
            return false;
    }
}
/*******2010-04-29
function checkEmail(str)
{
    //如果为空，则通过校验
    if(str == "")
        return true;
    if (str.charAt(0) == "." || str.charAt(0) == "@" || str.indexOf('@', 0) == -1
        || str.indexOf('.', 0) == -1 || str.lastIndexOf("@") == str.length-1 || str.lastIndexOf(".") == str.length-1)
        return false;
    else
        return true;
}
******/
function isValidEmail(emailStr){
	if(emailStr.length== 0){
		return true;
	}
	if(!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(emailStr))
		return false
	return true	
}

function getFloatFromStr(sString) {
    var sTemp = sString;
    var sCur="",ss="";

    for (var i=0; i<sTemp.length; i++) {
        ss = sTemp.substr(i,1);
        if (ss>="0" && ss<="9" || ss=="." || ss=="-") sCur += ss;
    }

    return sCur;
}
//control a textbox only can input number,set textbox onKeyDown execute this function.
/*function ctrlInputNumbOnly() {
	if (!((event.keyCode>=48 && event.keyCode<=57 && !event.shiftKey) || 
	      (event.keyCode>=96 && event.keyCode<=105) ||
	      (event.keyCode==8 || event.keyCode==9))) {
		event.returnValue=false;
	}
}
//set select option selected by key number
function ctrlNumbSelect(sel) {
	if ((event.keyCode>=48 && event.keyCode<=57 && !event.shiftKey) || //0-9
	    (event.keyCode>=65 && event.keyCode<=90 ) || //A-Z
	    (event.keyCode>=96 && event.keyCode<=122)) { //a-z
		var keyChar = String.fromCharCode(event.keyCode);
		for (var i=0; i<sel.length; i++) {
			if (sel.options[i].value == keyChar) {
				sel.options[i].selected = true;
				break;
			}
		} //end for loop
	}//end if
}
*/
/**set option item as selected*/
function setSelected(slt,sValue) {
	var str="";
	
	for (var i=0; i < slt.length; i++) {
		str = slt.options[i].value;
		if (str == sValue) {
			slt.options[i].selected = true;
			break;
		}
	}
}
/**select all or unselect all the grid checkbox
 * @param esrc ff.checkboxname
 * @param flag set as true or false, equals with check on or check off
 */
/*function changeSelected(esrc,flag) {
	if (esrc!=null && esrc.length!=null) {
		for (var i=0; i<esrc.length; i++) 
			esrc[i].checked = flag;
	} else if (esrc!=null) {
		esrc.checked = flag;
	}
}
*/
/**获取屏幕居中的位置，以字符串形式返回
 */
function getLeftTop(iWidth,iHeight) {
	var sWidth = window.screen.width;
	var sHeight= window.screen.height;
	var sLeft  = (sWidth - iWidth)/2;
	var sTop   = (sHeight - iHeight)/2;
	
	return ",left="+sLeft+",top="+sTop;
}

//将HTML实体替换回非法字符
function html2str(str) {
	if (str=="") return "";

	str = str.replaceAll("&amp;" ,"&");
	str = str.replaceAll("&#039;","'");
	str = str.replaceAll("&quot;","\"");
	str = str.replaceAll("&lt;"  ,"<");
	str = str.replaceAll("&gt;"  ,">");
	str = str.replaceAll("&#92;" ,"\\");
	str = str.replaceAll("&#64;" ,"@");
	str = str.replaceAll("&#42;" ,"*");

	return str;
}

function getSysTime() {
	var sp1 = "";
	var sp2 = "";
	var now = new Date();
	var sTime = ""  + now.getFullYear();
	    sTime+= sp1 + ((now.getMonth()+1)<10?"0"+(now.getMonth()+1):(now.getMonth()+1));
	    sTime+= sp1 + (now.getDate()   <10?"0"+now.getDate()   :now.getDate());
	    sTime+= ""  + (now.getHours()  <10?"0"+now.getHours()  :now.getHours());
	    sTime+= sp2 + (now.getMinutes()<10?"0"+now.getMinutes():now.getMinutes());
	    sTime+= sp2 + (now.getSeconds()<10?"0"+now.getSeconds():now.getSeconds());

	return sTime;
}

/** 与createGridObject1函数的功能一致，只是此函数自动设置Grid ID，只能用在单一Grid控件的情况
 *  参数与createGridObject1一致
 *@return Active Grid 对象
 */
/*function createGridObject(mydata,headCols,colShowLength) {
	return createGridObject1("gird99",mydata,headCols,colShowLength);
}
*/
/**创建Active Grid对象，在方法内设置了一些共用的属性和方法，在获取对象后还可以设置其他属性和方法
 * 必须定义active-row-highlight active-cell-highlight这两个CSS属性
 *@param gridID Grid控制的标识ID名，在同一个页面有多个Grid控件时，需要用此ID标识
 *@param mydata 是Gird数据，二维数组
 *@param headCols 是Grid表格的抬头Header
 *@param colShowLength 是Grid表格要显示列的长度，默认为headCols数组的长度
 *@return Active Grid 对象
 */
/*function createGridObject1(gridID,mydata,headCols,colShowLength){
	var obj = new Active.Controls.Grid;
	obj.setId(gridID);
	obj.setColumnHeaderHeight(22);  //set column header height

	obj.setRowProperty("count",mydata.length);
	obj.setColumnProperty("count",colShowLength);

	//set row data and column title
	obj.setDataProperty("text", function(i, j){return mydata[i][j];});
	obj.setColumnProperty("text",function(i)  {return headCols[i]});

	//allow multiple selection
	//obj.setSelectionProperty("multiple", true);
	
	var alternate = function() {
		return this.getRowProperty("order") % 2 ? "#F0F8FF" : "#FFFFFF";
	}
	//set mouse over row effect
	var row = new Active.Templates.Row;
	row.setEvent("onmouseover", "mouseover(this, 'active-row-highlight')");
	row.setEvent("onmouseout", "mouseout(this, 'active-row-highlight')");
    row.setStyle("background", alternate);
	obj.setTemplate("row",row);

	//set mouse over column effect
	var col = new Active.Templates.Text;
	col.setEvent("onmouseover","mouseover(this,'active-cell-highlight')");
	col.setEvent("onmouseout" ,"mouseout(this,'active-cell-highlight')");
	obj.setColumnTemplate(col);

	//re-initialize the grid data model
	obj.resetRowValues = function() {
		this.setRowProperty("count", mydata.length);
		this.setRowProperty("value", function(i){return i}); 
		this.setRowProperty("order", function(i){return i}); 
		this.setSortProperty("index", null); 
		this.setSelectionProperty("index", -1);
		this.setSelectionProperty("values", []);
		this.refresh();
	}
	//GET ROW AND COL WHEN CLICK
	//obj.setAction('click', function(src) { 
	//    iSelectedCol = src.getColumnProperty('index'); 
	//    iSelectedRow = src.getRowProperty('index'); 
	//});

	return obj;
}
*/
/**
 * 正确的日期时间格式是 YYYY-MM-DD HH24:MM，如果没有时间，则直接调用checkDateFormat函数校验日期。
 * @param  obj:输入日期字符串的Text对象，比如frm.strDate;
 * @param  isShow:是否显示错误提示框，true or false;
 * @param  position:当日期校验有问题时，用此字符串加上其他字符串给用户提示
 * @return 如果输入的不是有效的日期则给出错误提示并返回False；如果是正确的日期，则直接设置日期为 YYYY-MM-DD 格式的日期值. 
*/
/*function checkDateTime(obj,isShow,alertMesg) {
    var str = obj.value.replace(" 00:00:00","");
    str = str.replace(" 00:00","");
    if (str == "0000-00-00") {
        obj.value = "";
        return true;
    }

    var iPos = str.indexOf(":");
    if (iPos > 0) {
        var iIndex = str.indexOf(" ");
        if (iIndex > 0) {
            var sDate = str.substring(0,iIndex).trim();
            var iHour = parseInt(str.substring(iIndex,iPos).trim(),10);
            var iMinute = parseInt(str.substring(iPos+1,str.length),10);

            obj.value = sDate;
            if (!checkDateFormat(obj,isShow,alertMesg)) { //check date is valid
                obj.value = str;
                return false;
            }
            if (iHour<0 || iHour>23 || iMinute<0 || iMinute>59) {
                if (isShow) {
                    obj.value = str;
                    alert(alertMesg);
                    obj.focus();
                }
                return false;
            }
            obj.value = obj.value.trim()+" "+(iHour<10?"0"+iHour:iHour)+":"+(iMinute<10?"0"+iMinute:iMinute);
            return true;
        } else {
            if (isShow) {
                alert(alertMesg);
                obj.focus();
            }
            return false;
        }
    }
    else {
        return checkDateFormat(obj,isShow,alertMesg);
    }
}
*/
/**正确的日期格式是YYYY-MM-DD,YYYYMMDD,YYMMDD三种；
 * YYYYMMDD和YYMMDD格式将自动转换为YYYY-MM-DD格式
 * @param  obj:输入日期字符串的Text对象，比如frm.strDate;
 * @param  isShow:是否显示错误提示框，true or false;
 * @param  position:当日期校验有问题时，用此字符串加上其他字符串给用户提示
 * @return 如果输入的不是有效的日期则给出错误提示并返回False；如果是正确的日期，则直接设置日期为 YYYY-MM-DD 格式的日期值. 
 * @author wuguowen
 * @create 2008/08/02
 */
/*function checkDateFormat(obj,isShow,alertMesg) {
	var sYear="",sMonth="",sDay="";
	var iYear=0, iMonth=0, iDay=0;
	var sDate,newDate;
    var sp="-";

	if (obj==null || obj.value=="") {
		return true;
	} else
		sDate = obj.value;

	//split the "YYYYMMDD" and "YYMMDD" date to year,month,day.
	if ((sDate.length==8 || sDate.length==6) && sDate.indexOf(sp) < 0) {
		sDay   = sDate.substr(sDate.length-2,2);
		sMonth = sDate.substr(sDate.length-4,2);
		sYear  = sDate.substring(0,sDate.length-4);
	} else if (sDate.length==10 && sDate.indexOf(sp) > 0) {
		sYear  = sDate.substring(0,sDate.indexOf(sp));
		sMonth = sDate.substr(sDate.indexOf(sp)+1,2);
		sDay   = sDate.substr(sDate.lastIndexOf(sp)+1,2);
	} else {
		if (isShow) {
			alert(alertMesg);
			obj.focus();
		}
		return false;
	}

	if ( (sYear=="" || sMonth=="" || sDay=="") || !(checkIsInteger(sYear) && checkIsInteger(sMonth) && checkIsInteger(sDay)) ) {
		if (isShow) {
			alert(alertMesg);
			obj.focus();
		}
		return false;  //don't a valid date
	}
	if (sYear.length==2) {
		sYear = (parseInt(sYear,10)<50 ? "20"+sYear : "19"+sYear);  //the year > 2000 or year < 2000
	}
	iYear = parseInt(sYear,10);
	if (sMonth.indexOf("0")==0)	//the first char is "0"
		iMonth= parseInt(sMonth.substr(1,1),10) - 1;
	else 
		iMonth= parseInt(sMonth,10) - 1;
	if (sDay.indexOf("0")==0)
		iDay  = parseInt(sDay.substr(1,1),10);
	else
		iDay  = parseInt(sDay,10);	

	newDate = new Date(iYear,iMonth,iDay);
	if (newDate.getFullYear()==iYear && newDate.getMonth()==iMonth && newDate.getDate()==iDay) {
		obj.value = (sYear+sp+sMonth+sp+sDay);
		return true;
	} else {
		if (isShow) {
			alert(alertMesg);
			obj.focus();
		}
		return false;	//don't a valid date
	}
}
*/
/**日文平假名、片假名检查；英文、数字检查；可以单独检查，也可以综合检查。
 * @param mode=0~5; 0:检查是否日文平假名和片假名混合; 1:检查是否日文平假名; 2:检查是否日文片假名;
    3:检查是否英文和数字混合；4:检查是否英文;5:检查是否数字;6:检查是否是ASCII字符编码;8:非法字符的校验（‘，“，\）；
 * @param obj:フォームオブジェクト
 * @param isShow:是否显示错误提示框，true or false;
 * @param position:エラーメッセージの前半
 * @return 有効の場合はtrue、無効の場合はfalse
 */
function checkCharacter(mode,obj,isShow,alertMesg) {
	if (obj==null || obj.value=="") return true;
	var str = obj.value;
	var sReg,sAlert;

	switch (mode) {
		case 0: {sReg = /[^ぁ-んァ-ン\s]+/; break;}
		case 1: {sReg = /[^ぁ-ん\s]+/;      break;}
		case 2: {sReg = /[^ァ-ンー　\s]+/;  break;}
		case 3: {sReg = /[^A-Za-z0-9_-]+/;    break;}
		case 4: {sReg = /[^A-Za-z ]+/;      break;}
		case 5: {sReg = /[^0-9]+/;          break;}
		case 6: {sReg = /[^\040-\176]+/;    break;}
		//case 6: {sReg = /[^\040-\176]+/;   break;}
		case 7: {sReg = /[^?-?ー \s]+/;     break;}
		case 8: {sReg = /[\'|\"|\\]+/;   break;}
		default: return false;
	}
	if (str.match(sReg)) {
		if (isShow) {
			alert(html2str(alertMesg));
			obj.focus();
		}
		return false;
	} else {
		return true;
	}
}

/*function toggle_expand(anchor,id)
{
    var info;
    if (document.all)
        info = document.all.item(id);
    else if (document.getElementById)
        info = document.getElementById(id);
    else
        return false;

    if (info.style.display == "block")
    {
        info.style.display = "none";
        anchor.innerText = anchor.innerText.replace("▲","▼");
    }
    else if (info.style.display == "none")
    {
        info.style.display = "block";
        anchor.innerText = anchor.innerText.replace("▼","▲");
    }
}
*/
/**分页共通函数，与php的分页共通函数fn_getPageInfo配套使用。
 *如果在form里有定义action元素，则名称必须是strAction。如：
 * <input type="hidden" name="strAction" value="">
 * strCurrentPage hidden元素此共通函数会自动创建。
 *可以在具体的画面指定分页所在的form，以及设定form的action，target，method属性；方法如下：
 *page.form = ffmm;     //分页所在的form
 *page.formAction = ""; //要提交的程序文件的url地址
 *page.formTarget = ""; //_self or _top 或具体的frame名
 *page.formMethod = ""; //GET 或 POST
 */
/*function wupage() {
    this.form = null;      //form object
    this.formAction = "";  //form action url
    this.formTarget = "";  //default is _self
    this.formMethod = "";  //default is post

    wupage.prototype.go = function (iPage) {
        var i,j;
        var f=null,ff=this.form;

        if (ff == null) {
            for (i=0; i<document.forms.length; i++) {
                if (ff != null) {
                    break;
                }
                f = document.forms(i);
                for (j=0; j<f.all.length; j++) {
                    if (f.all(j).tagName=="A" && f.all(j).href.indexOf("page.go")>0) {
                        ff = f;
                        break;
                    }
                }
            }
        }
        if (ff != null) {
            if (this.formAction != "") {
                ff.action = this.formAction;
            }
            if (this.formTarget != "") {
                ff.target = this.formTarget;
            }
            if (this.formMethod.toUpperCase()=="GET" || this.formMethod.toUpperCase()=="POST") {
                ff.method = this.formMethod.toUpperCase();
            }

            if (ff.strAction != null) {
                ff.strAction.value = "SEARCH";
            }
            if (ff.strCurrentPage != null) {
                ff.strCurrentPage.value = iPage;
            } else {
                var cpage = document.createElement("<INPUT TYPE='hidden' NAME='strCurrentPage' VALUE=''>");
                ff.appendChild(cpage);
                ff.strCurrentPage.value = iPage;
            }
            ff.submit();
        }
    }
}
var page = new wupage();

function getFormClearElement(frm) {
    var obj = null;
    var js="",sTemp="";
    var maxLength = 0;

    for (var i=0; i<frm.elements.length; i++) {
        obj = frm.elements(i);
        if (obj.type=="text" || obj.tagName=="SELECT" || obj.tagName=="TEXTAREA") {
            sTemp = frm.name+"."+obj.name+".value";
            if (sTemp.length > maxLength) maxLength = sTemp.length;
        }
    }
    
    for (var i=0; i<frm.elements.length; i++) {
        obj = frm.elements(i);
        if (obj.type=="text" || obj.tagName == "SELECT") {
            sTemp = frm.name+"."+obj.name+".value";
            js += sTemp.strpad(" ",maxLength,"RIGHT") + "= \"\";\n";
        }
    }
    alert(js);
    window.clipboardData.setData("Text",js);
}
*/
//屏蔽BackSpace回退到之前请求页面
/****
document.onkeydown = function() {
    if (event.keyCode==8 && (event.srcElement.tagName!="INPUT" && event.srcElement.type!="text")
        && event.srcElement.tagName!="TEXTAREA") {
        event.cancelBubble = true;
        event.returnValue  = false;
        return false;
    }
    if ((event.ctrlKey) && (event.keyCode==78)) {  //屏蔽 Ctrl+n
        event.returnValue=false;
    }
    //当用户试图想通过ALT+F4组合键关闭窗口时候 则注销用户
    if ((window.event.altKey) && (window.event.keyCode==115)){
        
    }
}
*******/